const express = require('express')
const { User } = require('./models')
const jwt = require('jsonwebtoken')
const SECRET = 'weqeq34te342rfsv2343t4'// token的秘钥
const app = express()
app.use(express.json())// 使用json中间件以处理json

app.get('/api/users', async (req, res) => {
  const users = await User.find()
  res.send(users)
})

app.post('/api/register', async (req, res) => {
  const user = await User.create(req.body)
  res.send(user)
})

app.post('/api/login', async (req, res) => {
  const user = await User.findOne({
    username: req.body.username
  })
  if(!user){
    return res.status(422).send({
      msg: '用户名不存在'
    })
  }
  const isValid = require('bcrypt').compareSync(req.body.password, user.password)
  if(!isValid){
    return res.status(422).send({
      msg: '密码错误'
    })
  }

  // 生成token
  const token = jwt.sign({
    id: user._id// 将用户id混入token中
  }, SECRET)
  res.send({
    user,
    token
  })
})

// 中间件用于token验证
const auth = async (req, res, next) => {
  const token = req.headers.authorization
  const { id } = jwt.verify(token, SECRET)
  req.user = await User.findById(id)
  next()// 注意这里不用把req跟res传入，req跟res的沿用是自动处理的
}

app.get('/api/profile', auth, async (req, res) => {
  res.send(req.user)
})
app.listen('3000')